package com.ttc.mBackup.BackupAgent;

import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.ttc.mBackup.R;

public class BARScheduleType extends Activity implements OnClickListener {

	/*
	 * Define Widgets and Vars
	 *  image : show icon of Backup Schedule 
	 * listview : list item of Schedule Backup Type
	 * title : show what user choose to do task
	 * cont : widget to start or stop serivice backup
	 *cancel : button to finish this activity
	 *line :  show layoutlinear which contain cont and cancel button  
	 * typeS : hold int value of type of Schedule Backup 
	 *  		 * 0 : never
				 * 1 : daily
				 * 2 : weekly
				 * 3 : monthly
	 * CLOCK_DIALOG_ID, CALENDAR_DIALOG_ID, WEEK_DIALOG_ID :
	 *  hold int value which mark of dialog to show 
	 * 
	 * doM : ArrayList to save int value of day
	 * , it's added 1 for default day to backup Monthly 
	 * daysofweek : Days of week 
	 * checkitem : it's an array of Boolean to save which day is chosen to perform backup weekly
	 * For default : Mon,Web,Fri 
	 * doW : Save days of week for weekly backup 
				  
	*/
	
	  private static final String TAG = "BARScheduleType";
	private ImageView image;
	private ListView list;
	private TextView title;
	private Button cont,cancel;
	private LinearLayout line;
	private int typeS=0;
	private final int CLOCK_DIALOG_ID=0;
	private final int CALENDAR_DIALOG_ID=1;
	private final int WEEK_DIALOG_ID=2;
	private ArrayList<Integer> doM= new ArrayList<Integer>();
	private final String nametask[]={"Never","Daily","Weekly","Monthly"};
	
	
	private final String daysofweek[]={"Monday","TuesDay","Wednesday"
									   ,"Thrusday","Friday","Saturday","Sunday"};
	private boolean checkitem[] =  {true,false,true
			   ,false,true,false,false};
	
	private int hour=new Date().getHours();
	private int munite = new Date().getMinutes();
	
	
	
	private ArrayList<String> doW = new ArrayList<String>();
	private SharedPreferences prefs;
	private String pref_name="services";
	/*Service 
	 * Running : Service run or not
	 * */
	private boolean Running=false; 

	
	/*Key of value to send to Backup Schedule Service to do what backup schedule you want to do*/
	public static final String KEY_TYPE_SCHEDULE ="type";
	public static final String KEY_HOURS ="hours";
	public static final String KEY_MINUTE ="minute";
	public static final String KEY_WEEKLY ="weekly";
	public static final String KEY_MONTHLY ="monthly";
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.progresslayout);
		
		/*Get ID for Widget*/
		list = (ListView) findViewById(R.id.task_list);
		title=(TextView) findViewById(R.id.task_label);
		image = (ImageView) findViewById(R.id.tast_img);
		line = (LinearLayout) findViewById(R.id.laylinear);
		cont = (Button) findViewById(R.id.Cont_btn);
		cancel = (Button) findViewById(R.id.Cancle_btn);
		
		/*Set Visibility*/
		line.setVisibility(0);
		cont.setVisibility(0);
		cont.setEnabled(false);
		cancel.setVisibility(0);
		
		/*Check Service Run or not
		 * Get SharedPrefrences
		 * task is default item choice in listview*/
		Running=isMyServiceRunning();
		prefs = getSharedPreferences(pref_name,MODE_PRIVATE);
		int task = prefs.getInt(KEY_TYPE_SCHEDULE, 0);
		
		/*if service's running
		 * Set Button cont enable and settext Stop 
		 * also set text for title to show what backup schedule was chosen
		 * else 
		 * default set
		 * */
		if(Running)
		{
			cont.setEnabled(true);
			cont.setText("Stop");
			title.setText("Schedule's Setting :"+((task==1)?" Daily":(task==2?"Weekly":"Monthly")));
		}
		else
		{
			title.setText("Schedule is not Configed..");
			cont.setText("Start");
		}
		/*Set value and Atribute for Widget*/
		image.setImageResource(R.drawable.scheduleicon);
		
		/*
		 * Set Listener for ListView
		 * MultiChoice Mode
		 * Set Adapter
		 * */

		list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		list.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice,nametask));
		
		list.setItemChecked(prefs.getInt(KEY_TYPE_SCHEDULE, 0), true);
		list.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				/*
				 * 0 : never
				 * 1 : daily
				 * 2 : weekly
				 * 3 : monthly
				 * */
				Running=isMyServiceRunning();
				typeS=arg2;
				if(arg2>0&&!Running) cont.setEnabled(true);
				if(!Running){
				switch (arg2) {
				case 1: 
					
					title.setText("Backup Daily At "
									+prefs.getString(KEY_HOURS, 
													DateFormat.format("h:mmaa", new Date()).toString()));
					showDialog(CLOCK_DIALOG_ID); break;
				case 2:
					doW.add(daysofweek[0]);
					doW.add(daysofweek[2]);
					doW.add(daysofweek[4]);
					title.setText("Backup Weekly on "
							+prefs.getString(KEY_WEEKLY,"Monday,Wednesday,Friday"));
					showDialog(WEEK_DIALOG_ID);
					break;

				case 3:
					title.setText("Backup Weekly on "
							+prefs.getString(KEY_MONTHLY,"1"));
					showDialog(CALENDAR_DIALOG_ID);
					break;
				default : 
					if(!Running) cont.setEnabled(false);
					title.setText("Don't Have Any Configuration");
				}
			}
				else {
					list.setItemChecked(prefs.getInt(KEY_TYPE_SCHEDULE, 0), true);
					showToast("Service is Running!");}
			}
		});
		
		/*Set Listener For Button*/
		cont.setOnClickListener(this);
		cancel.setOnClickListener(this);
		
		
		
	}


	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		/*Show dialog to choose day of Week or Month to do something*/
		switch (id) {
		/*Weekly*/
		case WEEK_DIALOG_ID:
			AlertDialog.Builder alert = new AlertDialog.Builder(BARScheduleType.this);
		alert.setTitle("Choose Day of Week").setIcon(R.drawable.businessicon)
		.setPositiveButton("Set", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
				///Show Notice for user
				showToast("Set Days for Weekly Backup");
				String dayofW="";
				for(int i =0;i<doW.size();i++)
				{
					dayofW+= doW.get(i)+ ((i<doM.size()-1)?", ":"");
				}
				title.setText("Set Backup Monthly at " + dayofW);
				
				
			}
			
		}).setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
			}
		).setMultiChoiceItems(daysofweek, checkitem,
				new DialogInterface.OnMultiChoiceClickListener()
				{

					@Override
					public void onClick(DialogInterface dialog,
							int which, boolean isChecked) {
						// TODO Auto-generated method stub
						
						/*
						 * Set check value boolean to set
						 *  what days of week we do backup task
						 *  checkitem if which false and doW contain is remove
						 *  else add 
						 * 
						 * */
						checkitem[which]=isChecked;
						if(checkitem[which])
						{
							doW.add(daysofweek[which]);
							
						}
						else
						{
							if(doW.contains(daysofweek[which]))
							{
								doW.remove(daysofweek[which]);
							}
						}
						
					}
					});
			return alert.create();
/*Monthly*/
		case	CALENDAR_DIALOG_ID:
			
			/*Define Gridview to show List day on*/
		GridView view = new GridView(BARScheduleType.this);
		view.setNumColumns(GridView.AUTO_FIT);
		view.setVerticalSpacing(10);
		view.setHorizontalSpacing(10);
		view.setColumnWidth(30);
		view.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
		view.setGravity(Gravity.CENTER);
		
		
		view.setAdapter(new TextViewBase(BARScheduleType.this));
		
		/*Add Default Day Of Month to do backup*/
		doM.add(1);
		
		view.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
		
		/*set backup for check or uncheck textview */
		TextView textview = (TextView) arg0.getChildAt(arg2);
		if(doM.contains(arg2+1))
		{
			textview.setBackgroundColor(Color.rgb(51, 51, 51));
			doM.remove((Integer)(arg2+1));
		}
		else
		{
			textview.setBackgroundColor(Color.rgb(204, 204, 204));
			doM.add(arg2+1);
		}
			}
		});
	
		
		AlertDialog.Builder dialog = new AlertDialog.Builder(this); 
		dialog.setIcon(R.drawable.booicon).setTitle("Choose Day Of Month")	
				.setView(view)
				.setPositiveButton("Set", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
				///Show Notice for user
				showToast("Set Days for Monthly Backup");
				String days="";
				for(int i=0;i<doM.size();i++)
				{days+= String.valueOf(doM.get(i)) + ((i<doM.size()-1)?", ":"");}
				title.setText("Set Backup Monthly at " + days);
			}
		}).setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
			}
		)
		;
		return dialog.create();
		
		case CLOCK_DIALOG_ID :
			Date date = new Date();
			
			return new TimePickerDialog(this,mtimsetListener,date.getHours(),date.getMinutes(),false); 
		}
		return null;
	}

	/*Button onClickListener()
	 * Cont_btn :
	 * Running : true-> service runng or not
	 * 
	 * 
	 * */

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Button wid= (Button) v;
		Running=isMyServiceRunning();
		switch (wid.getId()) {
		case R.id.Cont_btn:
			
			/*Type fo Shedule*/
			switch (typeS) {
			case 0:
				if(!Running)
				{
				finish();
				}
				else
				{
					cont.setText("Start");
					Log.d(TAG, "onClick: stopping srvice");
				 saveservice(false);
				 cont.setEnabled(false);
				 
			      stopService( new Intent(this,MyServiceAgent.class));
				}
				break;
			case 1:
				if(!Running){
					Intent i = new Intent(this,MyServiceAgent.class);
					
					i.putExtra(KEY_TYPE_SCHEDULE,1);
					i.putExtra(KEY_HOURS, hour);
					i.putExtra(KEY_MINUTE, munite);
					
			/*	pendingIntent = PendingIntent.getService(BARScheduleType.this,
				    										requestCode,
				    										i,
				    										flags);*/
					saveservice(true);
					
					startService(i); 
					cont.setText("Stop");
					Log.d(TAG, "onClick: Starting srvice");	 
				}else
				{
					cont.setText("Start");
					Log.d(TAG, "onClick: stopping srvice");
					saveservice(false);
					cont.setEnabled(false);
			      stopService( new Intent(this,MyServiceAgent.class));
			      }
					break;
			case 2:
				if(!Running){
				Intent i1 =  new Intent(this,MyServiceAgent.class);
				i1.putExtra(KEY_TYPE_SCHEDULE,2);
				i1.putStringArrayListExtra(KEY_WEEKLY, doW);
				saveservice(true);
				
				startService(i1);
				cont.setText("Stop");
				Log.d(TAG, "onClick: Starting srvice");	
				}else
				{
					cont.setText("Start");
					Log.d(TAG, "onClick: stopping srvice");
					saveservice(false);
					cont.setEnabled(false);
			      stopService( new Intent(this,MyServiceAgent.class));
			      }
				break;
			case 3:
				if(!Running){
				Intent i2 =  new Intent(this,MyServiceAgent.class);
				i2.putExtra(KEY_TYPE_SCHEDULE,3);
				i2.putIntegerArrayListExtra(KEY_MONTHLY, doM);
		
				saveservice(true);
				startService(i2);
				cont.setText("Stop");
				Log.d(TAG, "onClick: Starting srvice");	
				}else
				{
					cont.setText("Start");
					Log.d(TAG, "onClick: stopping srvice");
					saveservice(false);
					cont.setEnabled(false);
			      stopService( new Intent(this,MyServiceAgent.class));
			      }
				break;
						
			
			}
			
			break;
		case R.id.Cancle_btn:
		finish();
			break;
		}
		
}
	/*Create Listener of ClockDialog*/
	private TimePickerDialog.OnTimeSetListener mtimsetListener = new TimePickerDialog.OnTimeSetListener() {
		
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// TODO Auto-generated method stub
			hour=hourOfDay;
			munite=minute;
			showToast("Daily Backup at "+hour+":"+munite);
			title.setText("Set Backup Daily at "+hour+":"+munite);
		}
	};
	
	/*Check Service Running*/
	private boolean isMyServiceRunning() 
	{
	    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
	        if ("com.ttc.mBackup.BackupAgent.MyServiceAgent".equals(service.service.getClassName())) {
	            return true;
	        }
	    }
	    return false;
	}
	
	/*Save info of your service*/
	private void saveservice(boolean SoL)
	{
		SharedPreferences prefs = getSharedPreferences(pref_name,MODE_PRIVATE);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putInt(KEY_TYPE_SCHEDULE, SoL?typeS:0);
		editor.putString(KEY_HOURS,SoL?(hour+" : "+munite):
			(new DateFormat().format("h:mmaa", new Date()).toString()));
		
		String dayofW="";
		for(int i =0;i<doW.size();i++)
		{
			dayofW+= doW.get(i)+ ((i<doM.size()-1)?", ":"");
		}
		editor.putString(KEY_WEEKLY,SoL?dayofW:"Monday, Wednesday, Friday");
		String dayofM="";
		for(int i=0;i<doM.size();i++)
		{
			
			dayofM+= String.valueOf(doM.get(i)) + ((i<doM.size()-1)?", ":"");
			
		}
		editor.putString(KEY_MONTHLY,SoL?dayofM:"1");
		
		editor.commit();
	}

	/*Show Toast*/
	private void showToast(String msg)
	{
	Toast toast=	Toast.makeText(BARScheduleType.this, msg, Toast.LENGTH_LONG );
	toast.setGravity(Gravity.CENTER, 0, 0);
	toast.show();
	}
}
